package com.bwie.controller;

import com.bwie.pojo.TbMenu;
import com.bwie.pojo.TbUser;
import com.bwie.service.TbUserService;
import com.bwie.utils.Result;
import com.bwie.vo.LoginVo;
import com.bwie.vo.PageUserVo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/user/index")
@Slf4j
public class IndexController {
    @Autowired
    TbUserService tbUserService;

    @Autowired
    HttpServletRequest request;

    @PostMapping("/login")
    public Result login(@RequestBody LoginVo loginVo){
        log.info("进入login方法");
        return tbUserService.login(loginVo);
    }

    @GetMapping("/code")
    public void code(){
        tbUserService.code();
    }

    @PostMapping("/sendCode/{mobile}/{code}")
    public Result sendCode(@PathVariable("mobile") String mobile,@PathVariable("code") String code){
        return tbUserService.sendCode(mobile,code);
    }

    @PostMapping("/loginMobile")
    public Result loginMobile(@RequestBody LoginVo loginVo){
        return tbUserService.loginMobile(loginVo);
    }

    @PostMapping("/getUserList")
    public Result getUserList(@RequestBody PageUserVo pageUserVo){
        return tbUserService.getUserList(pageUserVo);
    }

    @PostMapping("/uploadFile")
    public Result uploadFile(@RequestPart("file") MultipartFile file){
        return tbUserService.uploadFile(file);
    }

    @PostMapping("/updateUser")
    public Result updateUser(@RequestBody TbUser tbUser){
        return tbUserService.updateUser(tbUser);
    }

    @PostMapping("/getMenuById")
    public Result getMenuById(){
        String token = request.getHeader("token");
        if (token == null){
            return Result.error().setMsg("请先登录");
        }
        Claims body = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody();
        Integer userId = body.get("userId", Integer.class);

        List<TbMenu> menuList = tbUserService.getMenuById(userId);
        return Result.ok().setData(menuList);
    }

    @PostMapping("/deleteById/{userId}")
    public Result deleteById(@PathVariable("userId") Integer userId){
        return tbUserService.deleteById(userId);
    }

    @PostMapping("/deleteByIdAll")
    public Result deleteByIdAll(@RequestBody List<TbUser> userList){
        return tbUserService.deleteByIdAll(userList);
    }

    @PostMapping("/checkUser")
    public Result checkUser(@RequestBody TbUser tbUser){
        return tbUserService.checkUser(tbUser);
    }


}
